<?php

/**
 * Namespace for authentication
 *
 */
class Auth
{
    const NAME_FIELD = 'name';
    const PASSWORD_FIELD = 'password';
    
    /**
     * Test whether current user is logged in or not
     * @return boolean
     */
    public static function isLoggedIn()
    {
        $Session = Session::getInstance();
        return isset($Session['login']['OK']) ? $Session['login']['OK'] : false;
    }
    
    /**
     * Get a simple session login user
     * @return array
     */
    public static function getSimpleUser()
    {
        $Session = Session::getInstance();
        return $Session['login'];
    }
    
    /**
     * Login
     *
     * @param atring $username
     * @param string $password
     * @return bool success
     */
    public static function doLogin($username, $password)
    {
        if (!Validator::isName($username)) {
            throw new InvalidArgumentException('Invalid name');
        }
        if (!Validator::isNotEmpty($password)) {
            throw new InvalidArgumentException('No password given');
        }
        $DB = DB::getInstance()->getPrimary();
        $sql = sprintf("SELECT u.id, u.name, COUNT(*) AS isValid FROM ?pre%s AS u WHERE %s = '%s' AND %s = '%s'",
				User::TABLE,
				self::NAME_FIELD,
				$DB->escape($this->username),
				self::PASSWORD_FIELD,
				$DB->escape(hashPassword($this->password))
			);
		$user = $DB->getOne($sql);
		if ($user['isValid'] != 1) {
			sleep(5);
			return false;
		}
        $Session = Session::getInstance();
        if (!isset($Session['login'])) {
            $Session['login'] = array();
        }
        $LSession =& $Session['login'];
		$LSession['OK'] = true;
		$LSession['id'] = $user['id'];
		$LSession['name'] = $user[self::NAME_FIELD];
		return true;
    }
    
    /**
     * Logout (current usersession)
     *
     * @return bool
     */
    public static function doLogout()
    {
        $Session = Session::getInstance();
		$Session['login']['OK'] = false;
		return true;
    }
}